import xlwt

# from docx import Document


workbook = xlwt.Workbook(encoding='ascii')
worksheet = workbook.add_sheet('My Worksheet')
style = xlwt.XFStyle()  # 初始化样式
font = xlwt.Font()  # 为样式创建字体
font.name = 'Times New Roman'
font.bold = True  # 黑体
font.underline = False  # 下划线
font.italic = False  # 斜体字
style.font = font  # 设定样式

worksheet.write(0, 0, '题目', style)  # 带样式的写入
worksheet.write(0, 1, '作者', style)  # 带样式的写入
worksheet.write(0, 2, '期刊', style)  # 带样式的写入
worksheet.write(0, 3, '研究方法', style)  # 带样式的写入
worksheet.write(0, 4, '难度', style)  # 带样式的写入
worksheet.write(0, 5, '摘要', style)  # 带样式的写入
worksheet.write(0, 6, '主题', style)  # 带样式的写入

filename = "C:\\Users\\Forest\\Desktop\\1.9.1\\2.txt"  # txt文件和当前脚本在同一目录下，所以不用写具体路径
f = open(filename, encoding="utf-8")
# doc = Document(filename)

title = ''
author = ''
qikan = ''
method = ''
diff = ''
zy = ''
i = 0
for line in f.readlines():
    i = i + 1;
    num = 0
    # line=line.rstrip("\n")
    # print(line)
    if (line.startswith('题目') and len(line) > 3):
        title = line[3:]
        # print(title)
        # print('题目' + str(i))
        worksheet.write(i, 0, title, style)  # 带样式的写入
        # print(i)
    if (line.startswith('作者') and len(line) > 3):
        author = line[3:]
        # print('作者' + str(i))
        worksheet.write(i - 1, 1, author, style)  # 带样式的写入
        # print(author)
    if (line.startswith('期刊') and len(line) > 3):
        qikan = line[3:]
        # print('期刊' + str(i))
        worksheet.write(i - 2, 2, qikan, style)  # 带样式的写入
        # print(qikan)
    if (line.startswith('研究方法') and len(line) > 5):
        method = line[5:]
        worksheet.write(i - 3, 3, method, style)  # 带样式的写入
        # print(method)
    if (line.startswith('难度') and len(line) > 3):
        diff = line[3:]
        worksheet.write(i - 4, 4, diff, style)  # 带样式的写入
        # print(diff)
    if (line.startswith('摘要') and len(line) > 3):
        zy = line[3:]
        worksheet.write(i - 5, 5, zy, style)  # 带样式的写入
    if (line.startswith('主题') and len(line) > 3):
        zy = line[3:]
        worksheet.write(i - 6, 6, zy, style)  # 带样式的写入
        # print(zy)
    # else:
    #     print(line)
    #     continue
    workbook.save('formatting.xls')  # 保存文件
